/*
 * Copyright (c) United Binary LLC.  All rights reserved.
 * 
 * This code is licensed under the MIT License
 * 
 * SEE: http://harnessit.codeplex.com/license
 * 
 */
using System;
using System.Collections;
using System.Diagnostics;
using Microsoft.Win32;

namespace UnitedBinary.Core.Windows.Forms.Persistence
{
	/// <include file='Persistence.xml' path='/Docs/PersistentListViewColumnsState/Class/*'/>
	public class PersistentListViewColumnsState
	{
		private ArrayList columns = new ArrayList();
		private string keyPath = string.Empty;

		/// <include file='Persistence.xml' path='/Docs/PersistentListViewColumnsState/ctor/*'/>
		protected PersistentListViewColumnsState(string subKeyBaseName)
		{
			if (subKeyBaseName == null || subKeyBaseName.Length == 0)
			{
				System.ArgumentException e = new
					System.ArgumentException("Invalid SubKeyBaseName","SubKeyBaseName");
				e.Source = "PersistentListViewColumnsState class";
				throw e;
			}

			char[] chars = {'\\'};
			subKeyBaseName = subKeyBaseName.TrimStart(chars);
			subKeyBaseName = subKeyBaseName.TrimEnd(chars);
			keyPath = "Software\\" + subKeyBaseName + "\\" + "ListViewColumnsState";

			Debug.WriteLine("PersistentListViewColumnsState: Using registry key HKEY_CURRENT_USER\\"+keyPath);
		}

		private void SaveState(System.Windows.Forms.ColumnHeader header)
		{
			try
			{
				RegistryKey key = null;
				try
				{
					key = Registry.CurrentUser.CreateSubKey(keyPath);
					key.SetValue(header.Text, System.Math.Max(5, header.Width));
				}
				finally
				{
					if (key != null)
					{
						key.Close();
					}
				}
			}
			catch (Exception e)
			{
				Debug.WriteLine(e.ToString());
			}
		}

		/// <include file='Persistence.xml' path='/Docs/PersistentListViewColumnsState/Save/*'/>
		protected void Save(System.Windows.Forms.ListView listView)
		{
			foreach (System.Windows.Forms.ColumnHeader h in listView.Columns)
			{
				SaveState(h);
			}
		}

		private void Initalize(System.Windows.Forms.ColumnHeader header)
		{
			try
			{
				RegistryKey key = null;
				try
				{
					key = Registry.CurrentUser.OpenSubKey(keyPath);
					header.Width = Convert.ToInt32(key.GetValue(header.Text, header.Width));
				}
				finally
				{
					if (key != null)
					{
						key.Close();
					}
				}
			}
			catch (Exception e)
			{
				Debug.WriteLine(e.ToString());
			}
		}

		/// <include file='Persistence.xml' path='/Docs/PersistentListViewColumnsState/Initalize/*'/>
		protected void Initalize(System.Windows.Forms.ListView listView)
		{
			foreach (System.Windows.Forms.ColumnHeader h in listView.Columns)
			{
				Initalize(h);
			}
		}
	}
}
